<?php
/*
	Template Name: WP_Posts_API
*/

/**
 * WordPress Posts API
 * Creates an API for a blog's posts using HTTP requests.
 *
 * @author      Adrian Unger <unger.adrian@gmail.com>
 * @link        http://staydecent.ca
 * @license     http://www.opensource.org/licenses/mit-license.php MIT License
 * @version     0.0.4
 */
class WP_Posts_API
{
	private $query,
			$format,
			$posts = array(),
			$out;

	/**
	 * Checks PHP version, handle request
	 */
	public function __construct()
	{
		$this->handle_request();
	}

	/**
	 * Handles the HTTP Request
	 */
	private function handle_request()
	{
		$request = strtoupper($_SERVER['REQUEST_METHOD']);

		if($request === 'GET') {
			$this->query    = (isset($_GET['q']))   ? trim($_GET['q'], '/\\')   : '';
			$this->format   = (isset($_GET['qf']))  ? trim($_GET['qf'], '/\\')  : 'JSON';
		}
		elseif($request === 'POST') {
			$this->query    = (isset($_POST['q']))  ? trim($_POST['q'], '/\\')  : '';
			$this->format   = (isset($_POST['qf'])) ? trim($_POST['qf'], '/\\') : 'JSON';
		}
	}

	/**
	 * Loops through posts based on $this->query
	 */
	public function fetch_array()
	{  
		if(!function_exists('query_posts'))
			throw new Exception('Function &ldquo;query_posts$rdquo; does not exist. Please call within the WP Loop.');

		query_posts($this->query);

		while(have_posts()) {
			the_post();

			if(get_post_status() === 'publish') {
				$ID = get_the_id();

				$this->posts[$ID]['title']     = the_title(null, null, false);
				$this->posts[$ID]['date']      = the_date(null, null, null, false);
				$this->posts[$ID]['body']      = htmlentities(get_the_content());
				$this->posts[$ID]['category']  = get_the_category();
				$this->posts[$ID]['tags']      = get_the_tags();
				$this->posts[$ID]['author']    = get_the_author();
			}
		}

		return $this;
	}

	/**
	 * @todo Add more encode types
	 */
	public function format()
	{
		if(!isset($this->posts))
			throw new Exception('There is nothing to output. Please make sure your function calls are in sequence.');

		if($this->format === 'JSON') {
			$this->out = json_encode($this->posts);
		}

		if(isset($this->out))
			return $this;
		else
			return false;
	}

	/**
	 * Send the response
	 * @param string $err_msg error message, if exists we are sending an error response
	 */
	public function respond()
	{
		if(headers_sent())
			throw new Exception('Cannot send headers. Headers already sent.');

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		print($this->out);
	}

	/**
	 * Sends error response
	 */
	public function _error($err_msg)
	{
		if(isset($err_msg)) {
			$err_arr = array(
				'error_code' => '1',
				'error_msg' => $err_msg,
			);

			$this->out = json_encode($err_arr);
			$this->respond();
		}
	}
}

$WPPA = new WP_Posts_API;

try
{
	$output = $WPPA->fetch_array()->format()->respond();
}
catch(Exception $e)
{
	$WPPA->_error($e->getMessage());
}

?>